import $util from './util.js'
import Api from './api.js'

// 多图上传
function ChooseImage(num, stateText) {
	uni.chooseImage({
		count: num ? num : 9,
		sizeType: ['original', 'compressed'],
		sourceType: ['album', 'camera'],
		success: function(res) {
			var successUp = 0 //成功
			var failUp = 0 //失败
			var length = res.tempFilePaths.length //总数
			var count = 0 //第几张
			uploadOneByOne(res.tempFilePaths, successUp, failUp, count, length, stateText)
		},
	})
}

function uploadOneByOne(imgPaths, successUp, failUp, count, length, stateText) {
	var that = this
	uni.showLoading({
		title: '正在上传第' + count + '张',
	})
	uni.uploadFile({
		url: $util.Api + Api.upload.upload, //仅为示例，非真实的接口地址
		filePath: imgPaths[count],
		name: 'file', //示例，使用顺序给文件命名
		formData: {
			name: 'file'
		},
		success: function(e) {
			var jsonStr = e.data
			jsonStr = jsonStr.replace(" ", "")
			if (typeof jsonStr != 'object') {
				jsonStr = jsonStr.replace(/\ufeff/g, "") //重点
				var obj = JSON.parse(jsonStr)
			}
			if (stateText) {
				console.log(stateText, successUp, 333)
				var obja = {
					name: stateText,
					imgUrl: obj.data
				}
				// 最终获得图片得地址
				uni.$emit('gainImage_a', obja)
			} else {
				// 最终获得图片得地址
				uni.$emit('gainImage', obj.data)
			}
			successUp++ //成功+1
		},
		fail: function(e) {
			failUp++ //失败+1
		},
		complete: function(e) {
			count++ //下一张
			if (count == length) {
				//上传完毕，作一下提示
				uni.showToast({
					title: '上传成功' + successUp,
					icon: 'success',
					duration: 1000
				})
			} else {
				//递归调用，上传下一张
				uploadOneByOne(imgPaths, successUp, failUp, count, length, stateText)
			}
		}
	})
}

export default {
	ChooseImage,
	uploadOneByOne
}
